﻿using AutoMapper;
using Basic.Traceability.Domain.Slaughter;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.Slaughter.SlaughterEnterprise;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.Slaughter.SlaughterEnterprise
{
    public class CreateSlaughterEnterpriseHandler : IRequestHandler<CreateSlaughterEnterpriseCommand, APIResult<int>>
    {
        private readonly IBaseRepository<SlaughterEnterpriseModel> _slaughterEnterpriseRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateSlaughterEnterpriseHandler> _logger;

        public CreateSlaughterEnterpriseHandler(IBaseRepository<SlaughterEnterpriseModel> slaughterEnterpriseRepository, IMapper mapper, ILogger<CreateSlaughterEnterpriseHandler> logger)
        {
            _slaughterEnterpriseRepository = slaughterEnterpriseRepository;
            _mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 添加屠宰企业
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateSlaughterEnterpriseCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = _mapper.Map<SlaughterEnterpriseModel>(request);
            model.Id = YitIdHelper.NextId();
            var r = _slaughterEnterpriseRepository.Create(model);
            if (r > 0)
            {
                res.Msg = "添加屠宰企业信息成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                _logger.LogInformation("添加屠宰企业信息成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "添加屠宰企业信息失败";
                res.Data = r;
                res.Code = APIEnums.Fail;
                _logger.LogError("添加屠宰企业信息失败");
                return Task.FromResult(res);
            }
        }
    }
}
